package com.jims.api.v1.controller.patient;


import com.jims.master.common.data.Message;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.utils.CacheUtils;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.utils.SecurityUtil;
import com.jims.master.common.utils.UploadUtils;
import com.jims.master.common.web.BaseController;
import com.jims.master.modules.base.user.entity.MasterBaseinfo;
import com.jims.master.modules.base.user.entity.MasterDoctorinfo;
import com.jims.master.modules.base.user.service.MasterBaseinfoService;
import com.jims.master.modules.base.user.service.MasterContactinfoService;
import com.jims.master.modules.base.user.service.MasterDoctorinfoService;
import com.jims.master.modules.doctor.medicalService.entity.SDoctorServe;
import com.jims.master.modules.doctor.medicalService.service.SDoctorServeService;
import com.jims.master.modules.patient.myAttention.entity.PatFollow;
import com.jims.master.modules.patient.myAttention.service.PatFollowService;
import com.jims.master.modules.sync.entity.ClinicMaster;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.service.DictService;
import com.jims.master.modules.sys.service.SysLoginNameService;
import com.jims.master.modules.sys.service.UserService;
import com.jims.master.modules.sys.utils.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created 2017-05-18.
 * 用户信息基本信息维护
 *
 * @author jict
 * @version 2017-11-15
 */
@RestController
@RequestMapping(value = "user")
public class PatientMasterBaseController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private MasterBaseinfoService masterBaseinfoService;
    @Autowired
    private MasterContactinfoService masterContactinfoService;
    @Autowired
    private MasterDoctorinfoService masterDoctorinfoService;
    @Autowired
    private DictService dictService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysLoginNameService sysLoginNameService;
    @Autowired
    private PatFollowService patFollowService;
    @Autowired
    private SDoctorServeService sDoctorServeService;

    /**
     * @param userId
     * @return java.lang.String
     * @throws
     * @Title: getUserV100
     * @Description: （根据个人用户id获取用户信息）
     * @author jict
     * @date 2017-11-16
     */
    @RequestMapping(value = "V100/getUser", method = {RequestMethod.GET, RequestMethod.POST})
    public String getUser(@RequestParam(required = true) String userId) {
        Message msa = new Message();
        MasterBaseinfo masterBaseinfo = masterBaseinfoService.get(userId);
        masterBaseinfo.setSex(dictService.getDictName("10021",masterBaseinfo.getSex()));
        masterBaseinfo.setNation(dictService.getDictName("10003", masterBaseinfo.getNation()));
        masterBaseinfo.setMarried(dictService.getDictName("10004", masterBaseinfo.getMarried()));
        msa.setData(masterBaseinfo);
        return SecurityUtil.encryptMsgData(msa);
    }

    @RequestMapping(value = "V100/ceshi", method = {RequestMethod.GET, RequestMethod.POST})
    public String ceshi(@RequestParam(required = true) String userId) {
       /* Message msa = new Message();
        MasterBaseinfo masterBaseinfo = masterBaseinfoService.get(userId);
        msa.setData(masterBaseinfo);*/
        return "gg/haha";
    }

    /**
     * @param userId  用户id
     * @param myfiles 文件数组
     * @param picType 文件类型（头像，资格证照片）
     * @return
     * @throws
     * @Title:
     * @Description: （文件上传）
     * @author jict
     * @date 2017/11/20
     */
    @RequestMapping(value = "V100/upoad", method = {RequestMethod.GET, RequestMethod.POST})
    public String upoad(@RequestParam(required = true) String userId, @RequestParam("myfiles") MultipartFile[] myfiles, String picType, HttpServletRequest request) throws Exception {
        Message msa = new Message();
        StringBuffer sb = new StringBuffer();
        String datePath = DateUtils.formatDate(new Date(), "yyyy");
        //初始化上传文件路径
        String pathUrl = File.separator + datePath + File.separator + userId + File.separator + picType;
        for (int i = 0; i < myfiles.length; i++) {
            MultipartFile file = myfiles[i];
            String picUrl = UploadUtils.savePics(file, pathUrl, request);
            sb.append(picUrl + ",");
        }
        msa.setData(sb);
        return SecurityUtil.encryptMsgData(msa);
    }
     /**
       * @Title:
       * @Description: （个人信息维护）
       * @param userId  用户id
       * @param headPic  头像路径
       * @param height  身高
       * @param weight  体重
       * @return
       * @author jict
       * @date 2017/11/23
       * @throws
      */
    @RequestMapping(value = "V100/updateUser", method = {RequestMethod.GET, RequestMethod.POST})
    public String updateUser(@RequestParam(required = true) String userId, String headPic, String height, String weight, String name, String idCard) {
        Message msa = new Message();
        MasterBaseinfo masterBaseinfo = masterBaseinfoService.get(userId);
        if (headPic!=null) {
            masterBaseinfo.setHeadPath(headPic);
        }
        if (height!=null) {
            masterBaseinfo.setHeight(height);
        }
        if(weight!=null){
            masterBaseinfo.setWeight(weight);
        }
        if(name!=null){
            masterBaseinfo.setName(name);
        }
        if(idCard!=null){
            masterBaseinfo.setIdCard(idCard);
        }
        int result = masterBaseinfoService.save(masterBaseinfo);
        if (result==1) {
            msa.setData("修改成功");
        }else{
            msa.setData("修改失败");
        }
        return SecurityUtil.encryptMsgData(msa);
    }

     /**
       * @Title:
       * @Description: （保存身高体重）
       * @param userId 用户id
       * @param height 身高
       * @param weight 体重
       * @return
       * @author jict
       * @date 2017/12/13
       * @throws
      */
    @RequestMapping(value = "V100/healthNumber", method = {RequestMethod.GET, RequestMethod.POST})
    public String healthNumber(@RequestParam(required = true) String userId, String height, String weight) {
        Message msg = new Message();
        MasterBaseinfo masterBaseinfo = masterBaseinfoService.get(userId);
        if (height!=null) {
            masterBaseinfo.setHeight(height);
        }
        if(weight!=null){
            masterBaseinfo.setWeight(weight);
        }
        int result = masterBaseinfoService.save(masterBaseinfo);
        if (result==1) {
            msg.setData("修改成功");
        }else{
            msg.setData("修改失败");
        }
        return SecurityUtil.encryptMsgData(msg);
    }
    /**
     * @Title: bindingIdCardV100
     * @Description: （绑定身份证）
     * @param idCard
     * @return java.lang.String
     * @author WangYQ
     * @date 2017-11-17
     * @throws
     */
    @RequestMapping(value = "V100/bindingIdCard",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String bindingIdCard(@RequestParam(required = true)String mobile,@RequestParam(required = true)String idCard){
        Message msg=new Message();
        logger.debug("登录手机号："+mobile);
        logger.debug("缓存手机号："+CacheUtils.get("mobile"+mobile));
        if(mobile.equals(CacheUtils.get("mobile"+mobile))){
//            User user= userService.get(sysLoginNameService.findValidate(mobile));
            MasterBaseinfo masterBaseinfo=masterBaseinfoService.bindingIdCard(idCard,mobile);
            if(masterBaseinfo!=null){
                msg.setData(masterBaseinfo);
            }else {
                msg.setStatus("0");
                msg.setStatus("414");
                msg.setErrMsg("您输入的身份证号码已经存在");
            }
        }else{
            msg.setStatus("0");
            msg.setStatus("414");
            msg.setErrMsg("您输入的手机号码有误");
        }
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: findUserPatFollow
     * @Description: 查询用户关注的医生
     * @param personId
     * @return java.lang.String
     * @author jicunteng
     * @date 2018-4-18
     * @throws
     */
    @RequestMapping(value = "V100/findUserPatFollow",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String findUserPatFollow(@RequestParam(required = true)String personId,@RequestParam(required = true)String pageNo,String pageSize,HttpServletRequest request, HttpServletResponse response){
        Message msg=new Message();
        Page<PatFollow> page = new Page<PatFollow>();
        Map<String ,String> map = new HashMap<String, String>();
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        map.put("personId",personId);
        page = patFollowService.findUserPatFollow(new Page<PatFollow>(request, response), map);
//        List<PatFollow> list = patFollowService.findUserPatFollow(personId);
        List<PatFollow> list = page.getList();
        msg.setData(list);
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: saveUserPatFollow
     * @Description: 关注/取消关注操作
     * @param personId
     * @return java.lang.String
     * @author jicunteng
     * @date 2018-4-18
     * @throws
     */
    @RequestMapping(value = "V100/saveUserPatFollow",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String saveUserPatFollow(@RequestParam(required = true)String personId,@RequestParam(required = true)String doctorId,@RequestParam(required = true)String status){
        Message msg=new Message();
        PatFollow patFollow = new PatFollow();
        patFollow.setDoctorId(doctorId);
        patFollow.setPersonId(personId);
        int i=0;
        PatFollow patFollow1 = patFollowService.getPatFollowByUser(patFollow);
        if(patFollow1!=null){
            if(patFollow1.getFollowFlag().equals(status)){
                msg.setStatus("2");
            }else{
                patFollow1.setFollowFlag(status);
                i= patFollowService.save(patFollow1);
                if (i>0) {
                    msg.setStatus("1");
                }else{
                    msg.setStatus("0");
                }
            }
        }else{
            patFollow.setFollowFlag(status);
            i= patFollowService.save(patFollow);
            if (i>0) {
                msg.setStatus("1");
            }else{
                msg.setStatus("0");
            }
        }
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: isPatFollow
     * @Description: 查询该用户是否关注此医生
     * @param personId
     * @return java.lang.String
     * @author jicunteng
     * @date 2018-4-18
     * @throws
     */
    @RequestMapping(value = "V100/isPatFollow",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String isPatFollow(@RequestParam(required = true)String personId,@RequestParam(required = true)String doctorId){
        Message msg=new Message();
        PatFollow patFollow = new PatFollow();
        patFollow.setDoctorId(doctorId);
        patFollow.setPersonId(personId);
        PatFollow patFollow1 = patFollowService.getPatFollowByUser(patFollow);
        if(patFollow1!=null&&!"".equals(patFollow1)&&patFollow1.getFollowFlag().equals("1")){
            msg.setStatus("1");
        }else {
            msg.setStatus("2");
        }
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: doorToDoor
     * @Description: 医生上门服务
     * @param doctorId
     * @return java.lang.String
     * @author jicunteng
     * @date 2018-4-18
     * @throws
     */
    @RequestMapping(value = "V100/doorToDoor",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String doorToDoor(@RequestParam(required = true)String doctorId){
        Message msg=new Message();
        List<SDoctorServe> sDoctorServeList=sDoctorServeService.serveListByDoctor(doctorId);
        msg.setData(sDoctorServeList);
        return SecurityUtil.encryptMsgData(msg);
    }

    /**
     * @Title: addRelativesFriends
     * @Description: 医生上门服务
     * @param mobile
     * @param idCard
     * @param name
     * @return java.lang.String
     * @author WangYQ
     * @date 2018-6-23
     * @throws
     */
    @RequestMapping(value = "V100/addRelativesFriends",method ={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String addRelativesFriends(@RequestParam(required = true)String mobile,@RequestParam(required = true)String idCard,@RequestParam(required = true)String name){
        Message msg=new Message();
        MasterBaseinfo masterBaseinfo=masterBaseinfoService.addRelativesFriends(mobile,idCard,name);
        msg.setData(masterBaseinfo);
        return SecurityUtil.encryptMsgData(msg);
    }
}
